package com.win.servlet;

import com.win.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @Author:
 * @Date: 2024/7/19 12:53
 * @Description:
 */
public class SessionDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 请求字符编码
        req.setCharacterEncoding("utf-8");
        // 响应字符编码
        resp.setCharacterEncoding("utf-8");
        // 将text转html
        resp.setContentType("text/html;charset=utf-8");


        // 获取sessionId
        HttpSession session = req.getSession();
        String sessionId = session.getId();
        //判断SessionId是不是新的
        if (session.isNew()) {
            resp.getWriter().write("Session创建成功："+sessionId);
        }else {
            resp.getWriter().write("Session已经存在，id："+sessionId);
        }

        // 存入String
        session.setAttribute("name","win");
        // 存入对象
        User user = new User(1,"张三","123456");
        session.setAttribute("user",user);


        //猜想session在创建的时候做了什么,要不然不会在cookie中看到他
        Cookie jseesionid = new Cookie("JSEESIONID", sessionId);
        resp.addCookie(jseesionid);

    }
}
